package ngames.com.sushitv.net.okhttp.callback;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/1/19.
 */
public abstract class RequestCallBack<T> {
    protected static final int MSG_SUCCESS = 0;
    protected static final int MSG_FAILURE = 1;
    protected static final int MSG_PROGRESS = 2;

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SUCCESS:
                    onSuccess((T) msg.obj);
                    break;
                case MSG_FAILURE:
                    onFailure((String) msg.obj, null);
                    break;
                case MSG_PROGRESS:
                    onProgress(msg.arg1);
                    break;
            }
        }
    };

    /**
     * UI Thread
     * @param call
     * @param tag
     */
    public void onBefore(Call call, String tag) {

    }

    /**
     * UI Thread
     *
     * @param progress
     */
    public void onProgress(int progress) {

    }

    public void progress(int progress) {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_PROGRESS, progress, 0));
    }

    public void failure(final String code, final String msg) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                onFailure(code, msg);
            }
        });
    }

    protected void success(T obj) {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SUCCESS, obj));
    }

    /**
     * Thread Pool Thread
     *
     * @param response
     */
    public abstract T parseResponse(Response response);

    public abstract void onFailure(String code, String msg);

    public abstract void onSuccess(T obj);
}
